/* eslint-disable react/prop-types */
import React, { Component } from 'react';
import ListEmpty from 'atComponents/ListEmpty';
import { Button, Tab, Message } from '@teamix/ui';
import { Header, Content, Body, OperationBar, BodyContent } from '@alife/devops-ui';
import { navigate } from 'utils/router';
import ListLoading from 'atComponents/ListLoading';
import docs from 'utils/docs';
import MonitorSwitch from './switch';
import RecordTable from './recordTable';
import WhitelistTable from './whitelistTable';
import utils from 'utils';
import { enterPage, Perf } from 'utils/track';
import './index.scss';
import Moment from 'moment';
import BillingStatus from 'components/billing';
import BillingMessage from 'components/billing/message';
import WatermarkDemo from './Watermark';
// import PremiumService from 'components/premiumService';
import intl from '../../../../../../../../../../locale';

const NOTIFI_METHODS = {
  IN_SITE: intl.get({
    id: 'code-assets.containers.sensitiveBehaviorMonitor.ZhanNeiXin',
    defaultMessage: '站内信',
  }),

  EMAIL: intl.get({
    id: 'code-assets.containers.sensitiveBehaviorMonitor.Mailbox',
    defaultMessage: '邮箱',
  }),

  DINGDING: intl.get({
    id: 'code-assets.containers.sensitiveBehaviorMonitor.Dingtalk',
    defaultMessage: '钉钉',
  }),
};

export default class Root extends Component {
  constructor(props) {
    super(props);
    let activeTab = 'record';
    const query = this.props.location.search || '';
    if (query !== '') {
      const nav = utils.getUrlSearchParam('nav') || '';
      if (nav != null) {
        if (nav === 'record') {
          activeTab = 'record';
        } else if (nav === 'whitelist') {
          activeTab = 'whitelist';
        }
      }
    }
    this.state = {
      activeTab,
      activeValue: 'sensitive',
    };
  }

  componentDidMount() {
    // 获取开关设置
    this.props.getSensitiveSetting();
    this.props.getSecuritySettingData();
    document.title = intl.get({
      id: 'code-assets.containers.sensitiveBehaviorMonitor.MemberBehaviorSecurityCloudEffect',
      defaultMessage: '成员行为安全 · 云效 Codeup',
    });

    enterPage('Organization-Settings-Security-Member behavior monitoring', {
      sendPerf: false,
    });
  }

  openSecurityNotifyPage = () => {
    navigate('/settings/security_notify');
  };

  getNotifyMethod = (notify_method) => {
    const notifyArr = notify_method ? notify_method.split(',') : [];
    let str = '';
    for (const idx in notifyArr) {
      str += intl.get(
        {
          id: 'code-assets.containers.sensitiveBehaviorMonitor.Notifimethodsnotifyarr',
          defaultMessage: '{NOTIFIMETHODSNotifyArr}、',
        },

        { NOTIFIMETHODSNotifyArr: NOTIFI_METHODS[notifyArr[idx]] },
      );
    }
    str = str.endsWith('、') ? str.substring(0, str.length - 1) : str;
    return str;
  };

  renderEnableTips = (notify_method) => {
    const notifyMethod = this.getNotifyMethod(notify_method);
    return (
      <Message
        style={{ marginBottom: 20 }}
        className="sensitive-notification-msg-outer"
        key="SensitiveNotificationMsg"
        type="notice"
        title={
          <div className="sensitive-notification-msg">
            <span style={{ flex: 1 }}>
              {notifyMethod
                ? intl.get(
                    {
                      id: 'code-assets.containers.sensitiveBehaviorMonitor.NotifymethodNotificationsThatHaveSubscribed',
                      defaultMessage: '已订阅敏感行为告警的{notifyMethod}通知',
                    },

                    { notifyMethod },
                  )
                : intl.get({
                    id: 'code-assets.containers.sensitiveBehaviorMonitor.NotSubscribedToSensitiveBehavior',
                    defaultMessage: '未订阅敏感行为告警',
                  })}
            </span>
            <Button
              className="sensitive-notification-msg-btn"
              type="primary"
              text
              onClick={this.openSecurityNotifyPage}
            >
              {notifyMethod
                ? intl.get({
                    id: 'code-assets.containers.sensitiveBehaviorMonitor.ModifySubscription',
                    defaultMessage: '修改订阅',
                  })
                : intl.get({
                    id: 'code-assets.containers.sensitiveBehaviorMonitor.GoToSubscription',
                    defaultMessage: '前往订阅',
                  })}
            </Button>
          </div>
        }
        shape="inline"
        closeable
      />
    );
  };

  renderDisabledTips = () => {
    return (
      <ListEmpty
        className={'sensitiveBehavior-disabled-tips'}
        content="未执行监测，立即开启吧"
        description={
          <div>
            <div>
              {intl.get({
                id: 'code-assets.containers.sensitiveBehaviorMonitor.SensitiveBehaviorMonitoringHelpsEnterprises',
                defaultMessage: '敏感行为监测帮助企业第一时间发现成员的异常性敏感行为，',
              })}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {intl.get({
                id: 'code-assets.containers.sensitiveBehaviorMonitor.HelpsAdministratorsProtectCodeAssets',
                defaultMessage: '帮助管理者守护代码资产安全',
              })}{' '}
              <Button
                type="primary"
                text
                component="a"
                target="_blank"
                href={docs('securityRiskControl')}
                style={{ marginLeft: 8 }}
              >
                {intl.get({
                  id: 'code-assets.containers.sensitiveBehaviorMonitor.LearnMore',
                  defaultMessage: '了解更多',
                })}
              </Button>
            </div>
          </div>
        }
        image="https://img.alicdn.com/tfs/TB156JqnND1gK0jSZFsXXbldVXa-300-300.png"
      />
    );
  };

  onTabChange = (value) => {
    this.setState({
      activeTab: value,
    });
  };

  BillingHanderRender = () => {
    const { enterprisePackage } = this.props;
    const billingStatus = enterprisePackage && enterprisePackage.status;
    const billingPlanType = enterprisePackage && enterprisePackage.plan_type;
    const billingTryOrder =
      (enterprisePackage && enterprisePackage.is_can_use_trial_feature) ||
      (enterprisePackage && enterprisePackage.is_has_used_trial_feature);
    const billingnewS =
      billingPlanType === 'premiumVersion' &&
      (billingStatus === 'limit' || billingStatus === 'strictLimit');

    if (billingnewS) {
      return (
        <BillingStatus
          visi
          status={billingStatus}
          biObj={enterprisePackage}
          isClose={!billingnewS}
          billingOpenHander={this.props.getOrgplan}
        />
      );
    } else if (billingPlanType !== 'premiumVersion' && billingTryOrder) {
      return (
        <BillingStatus
          visi
          status={billingStatus}
          biObj={enterprisePackage}
          isClose={!billingnewS}
          billingOpenHander={this.props.getOrgplan}
        />
      );
    }
  };

  onChangeHander = (value) => {
    this.setState({
      activeValue: value,
    });
  };

  render() {
    const { is_sensitive_behavior_enable, getSensitiveSettingEnd, notify_method } = this.props;
    const { activeValue, activeTab } = this.state;

    const { enterprisePackage } = this.props;
    const billing =
      enterprisePackage && enterprisePackage.order_info && enterprisePackage.order_info.order_id;
    const billingValue = billing
      ? Moment(enterprisePackage.order_info.end_date).diff(Moment(), 'day')
      : 0;
    const biValueStatus = billingValue < 0;

    if (!getSensitiveSettingEnd) {
      return <ListLoading />;
    }

    const optBar = (
      <OperationBar>
        <Tab onChange={this.onChangeHander} activeKey={activeValue} animation={false}>
          <Tab.Item title={<span>敏感行为监测</span>} key={'sensitive'} />
          <Tab.Item title={<span>安全水印</span>} key={'watermark'} />
        </Tab>
      </OperationBar>
    );

    const content = (
      <Content style={{ position: 'relative' }}>
        {activeValue === 'sensitive' ? (
          <div className="sensitive-monitor-page">
            <MonitorSwitch {...this.props} />
            {is_sensitive_behavior_enable ? (
              <div>
                {this.renderEnableTips(notify_method)}
                <Tab onChange={this.onTabChange} activeKey={activeTab} shape="capsule">
                  <Tab.Item title={<span>敏感行为记录</span>} key={'record'} />
                  <Tab.Item title={<span>监测白名单</span>} key={'whitelist'} />
                </Tab>
                {activeTab === 'record' ? (
                  <RecordTable {...this.props} />
                ) : (
                  <WhitelistTable {...this.props} />
                )}
              </div>
            ) : (
              this.renderDisabledTips()
            )}
            <Perf page="Organization-Settings-Security-Member behavior monitoring" />
          </div>
        ) : (
          <WatermarkDemo />
        )}
      </Content>
    );

    let renderRes = [optBar, content];
    const { pathname } = window.location;
    if (pathname === '/risk_control') {
      renderRes = (
        <Body>
          <BodyContent>
            {optBar}
            {content}
          </BodyContent>
        </Body>
      );
    }

    return (
      <React.Fragment>
        {this.BillingHanderRender()}
        {billing && !biValueStatus && <BillingMessage moment={billingValue} />}
        <>
          <Header
            title={intl.get({
              id: 'code-assets.containers.sensitiveBehaviorMonitor.MemberBehaviorSecurity',
              defaultMessage: '成员行为安全',
            })}
            className={`${billing && !biValueStatus ? 'after-billingMessage' : ''}`}
          />
          {renderRes}
        </>
      </React.Fragment>
    );
  }
}
